﻿using System;
using MagickNet;
using MagickServer.Utils;

namespace MagickServer.Services {
    public class CachingImageSource : IImageSource {
        private readonly IImageSource source;
        private readonly ICache cache;

        public CachingImageSource(IImageSource source, ICache cache) {
            this.source = source;
            this.cache = cache;
        }

        public Image GetImage(string key) {
            var bytes = cache[key] as byte[];
            if (bytes == null) {
                var img = source.GetImage(key);
                bytes = img.ToByteArray();
                cache[key] = bytes;
            }
            using (var blob = new Blob(bytes))
                return new Image(blob);
        }
    }
}